//
//  ETProjectApplicationAlertController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/11/3.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

enum ETProjectApplicationAlertStyle {
    case add    //劳务公司添加民工到项目
    case apply  //民工主动申请的调入
}
class ETProjectApplicationAlertController: UIViewController {
    

    fileprivate var coverView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        return view
    }()
    
    fileprivate var panelView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = 6
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOpacity = 0.3
        view.layer.shadowOffset = CGSize(width: 1, height: 1)
        view.backgroundColor = UIColor.white
        return view
    }()
    
    fileprivate var titleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .center
        label.font = UIFont(name: "PingFangSC-Regular", size: 18)
        label.textAlignment = .center
        return label
    }()
    
    fileprivate var salaryLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont(name: "PingFangSC-Regular", size: 18)
        return label
    }()
    
    fileprivate var workingHourEverydayLable: UILabel = {
        let label = UILabel()
        label.font = UIFont(name: "PingFangSC-Regular", size: 18)
        return label
    }()
    
    fileprivate var okButton: UIButton = {
        let button = UIButton()
        button.setTitle("确认", for: .normal)
        button.setTitleColor(UIColor.mg_blue, for: .normal)
        return button
    }()
    
    private var okHandler: (()->Void)?
    
    // titleLabel内容
    fileprivate var titleLabelString: String {
        get {
            var str = ""
            str += self.companyName ?? "--"
            if self.style == .apply {
               str +=  "劳务公司同意您申请调入的"
            }
            else {
                str +=  "劳务公司把您拉入了"
            }
            str += projectName ?? "--"
            str += "项目"
            return str
        }
    }
    
    //salaryLabel内容
    fileprivate var salaryLabelString: NSMutableAttributedString {
        get {
            var string = "工资："
            string += self.daySalary ?? "--"
            string += "元/天"
            let mutableAttributedString = NSMutableAttributedString.init(string: string)
            mutableAttributedString.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.red], range: NSRange.init(location: 3, length: string.characters.count - 3))
            return mutableAttributedString
        }
    }
    
    //workingHourEverydayLable内容
    fileprivate var workingHourString: String {
        get {
            var string = "每日工作时长："
            string += self.workHours ?? "--"
            string += "小时"
            return string
        }
    }
    
    var companyName: String?
    var daySalary: String?
    var projectName: String?
    var workHours: String?
    
    //当前alert是否正在显示
    private var isShowing:Bool = false
    
    var style: ETProjectApplicationAlertStyle!
    
    init (_  okHandler: @escaping ()-> Void){
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.okHandler = okHandler
    }
    
    init ( dict: [String: Any], style: ETProjectApplicationAlertStyle){
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        
        self.style = style
        self.analysis(dict)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.okButton.addTarget(self, action: #selector(doOkButtonAction), for: .touchUpInside)
        
        self.setupViews()
        self.updateView()
        
        self.isShowing = true
    }
    
    deinit {
        self.isShowing = false
    }
    
    private func setupViews() {
        self.view.addSubview(self.coverView)
        self.coverView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        self.view.addSubview(self.panelView)
        self.panelView.snp.makeConstraints { (make) in
            make.left.equalTo(45)
            make.right.equalTo(-45)
            make.centerX.equalTo(self.view)
            make.centerY.equalTo(self.view)
        }
        
        self.panelView.addSubview(self.titleLabel)
        self.titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.panelView).offset(15)
            make.left.equalTo(self.panelView).offset(10)
            make.right.equalTo(self.panelView).offset(-10)
        }
        
        self.panelView.addSubview(self.salaryLabel)
        self.salaryLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.panelView).offset(10)
            make.right.equalTo(self.panelView).offset(-10)
            make.top.equalTo(self.titleLabel.snp.bottom).offset(15)
        }
        
        self.panelView.addSubview(self.workingHourEverydayLable)
        self.workingHourEverydayLable.snp.makeConstraints { (make) in
            make.left.equalTo(self.panelView).offset(10)
            make.right.equalTo(self.panelView).offset(-10)
            make.top.equalTo(self.salaryLabel.snp.bottom).offset(5)
        }
        
        let horizontalLine1 = UIView()
        horizontalLine1.backgroundColor = UIColor(red: 243/255, green: 243/255, blue: 243/255, alpha: 1)
        self.panelView.addSubview(horizontalLine1)
        horizontalLine1.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.panelView)
            make.top.equalTo(self.workingHourEverydayLable.snp.bottom).offset(15)
            make.height.equalTo(1)
        }
        
        self.panelView.addSubview(self.okButton)
        self.okButton.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.panelView)
            make.top.equalTo(horizontalLine1.snp.bottom).offset(5)
            make.bottom.equalTo(self.panelView).offset(-5)
        }
    }
    
    private func updateView() {
        self.titleLabel.text = self.titleLabelString
        self.salaryLabel.attributedText = self.salaryLabelString
        self.workingHourEverydayLable.text = self.workingHourString
    }
    
    private func analysis(_ dict: [String: Any]) {
        self.companyName = dict["CompanyName"] as? String
        if let daySalary = dict["DaySalary"] {
            let daySalaryString = "\(daySalary)"
            self.daySalary = String.init(format: "%.2f", Float(daySalaryString)!)
        }
        self.projectName = dict["ProjectName"] as? String
        
        if let workHours = dict["WorkHours"] {
            let workHoursString = "\(workHours)"
            self.workHours = String.init(format: "%.2f", Float(workHoursString)!)
        }
    }
    
    @objc private func doOkButtonAction() {
        self.dismiss(animated: true, completion: nil)
    }
}
extension ETProjectApplicationAlertController: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return ProjectApplicationControllerTransitionPresent()
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return ProjectApplicationControllerTransitionDismiss()
    }
}

class ProjectApplicationControllerTransitionPresent: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromView = transitionContext.view(forKey: .from)
        let toVc = transitionContext.viewController(forKey: .to) as! ETProjectApplicationAlertController
        let container = transitionContext.containerView
        container.addSubview(toVc.view)
        
        let panelView = toVc.panelView
        let coverview = toVc.coverView
        coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        panelView.alpha = 0.3
        panelView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
        UIView.animate(withDuration:0.1, animations: {
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.3)
            panelView.transform = CGAffineTransform.identity
            panelView.alpha = 1
        }) { (finish) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            toVc.view.addSubview(fromView!)
            toVc.view.sendSubview(toBack: fromView!)
        }
    }
}

class ProjectApplicationControllerTransitionDismiss: NSObject,UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromVc = transitionContext.viewController(forKey: .from) as! ETProjectApplicationAlertController
        
        //        let panelView = fromVc.panelView
        let coverview = fromVc.coverView
        UIView.animate(withDuration: 0.1, animations: {
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        }) { (_) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
}
